﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;

namespace CodeIn.Modules.Ui.FileExplorer {
	public partial class FileExplorerView : UserControl {
		public FileExplorerView() {
			InitializeComponent();
		}

		private void OnIconMouseDown(object sender, MouseButtonEventArgs e) {
			DependencyObject item = sender as DependencyObject;
			while (!(item is TreeViewItem))
				item = VisualTreeHelper.GetParent(item);
			TreeViewItem tvitem = (TreeViewItem)item;
			tvitem.IsExpanded = !tvitem.IsExpanded;
		}

		private void OnItemMouseRightButtonDown(object sender, MouseButtonEventArgs e) {
			TreeViewItem item = (TreeViewItem)sender;
			item.IsSelected = true;
			e.Handled = true;
		}

		private void OnItemMouseDoubleClick(object sender, MouseButtonEventArgs e) {
			TreeViewItem item = (TreeViewItem)sender;
			var vm = (FileExplorerItemViewModel)item.DataContext;

			if (vm.IsSelected &&
				(vm.Type == FileExplorerItemViewModel.Types.DIRECTORY
				|| vm.Type == FileExplorerItemViewModel.Types.DRIVE)) {
					vm.IsExpanded = !vm.IsExpanded;
			}

			if (vm.IsSelected && vm.Type == FileExplorerItemViewModel.Types.FILE) {
				if (vm.ContextMenu.Items.Count > 0) {
					MenuItem menuItem = (MenuItem)vm.ContextMenu.Items[0];
					if (vm.LaunchContextMenuActionCommand.CanExecute(menuItem.CommandParameter))
						vm.LaunchContextMenuActionCommand.Execute(menuItem.CommandParameter);
				}
			}

			e.Handled = true;
		}

		private void OnItemSelected(object sender, RoutedEventArgs e) {
			((TreeViewItem)e.OriginalSource).BringIntoView();
		}
	}
}
